<?php

/*
 * Copyright (c) 2009 Nguyen Duc Thuan <me@ndthuan.com>
 * All rights reserved.
 */

class Fete_View_Control_DataList
{
    protected $_datarows        = array();
    protected $_header          = '';
    protected $_footer          = '';
    protected $_rowTemplate     = '';
    protected $_alterRowTemplate    = null;

    /**
     *
     * @param array $datarows
     * @return Fete_View_Control_DataList
     */
    public static function getInstance($datarows)
    {
        return new self($datarows);
    }

    public function __construct($datarows = array())
    {
        $this->setDatarows($datarows);
    }

    /**
     *
     * @param array $datarows
     * @return Fete_View_Control_DataList
     */
    public function &setDatarows($datarows)
    {
        $this->_datarows = $datarows;

        return $this;
    }

    /**
     *
     * @param string $template
     * @return Fete_View_Control_DataList
     */
    public function &setRowTemplate($template)
    {
        $this->_rowTemplate = $template;

        return $this;
    }

    /**
     *
     * @param string $template
     * @return Fete_View_Control_DataList
     */
    public function &setAlterRowTemplate($template)
    {
        $this->_alterRowTemplate = $template;

        return $this;
    }

    public function &setHeader($header)
    {
        $this->_header = $header;

        return $this;
    }

    public function &setFooter($footer)
    {
        $this->_footer = $footer;

        return $this;
    }

    /**
     *
     * @return string
     */
    public function getString()
    {
        $output = $this->_header;

        foreach ($this->_datarows as $offset => $row)
        {
            $rowCounter = $offset + 1;
            $reminder   = $rowCounter % 2;

            if (0 === $reminder && null !== $this->_alterRowTemplate) {
                $template = $this->_alterRowTemplate;
            } else {
                $template = $this->_rowTemplate;
            }

            $template = str_replace('%counter%', $rowCounter, $template);
            $template = preg_replace('#(\$(.+?)\$)#sie', 'isset($row["\\2"]) ? $row["\\2"] : \'\\1\'', $template);
            preg_match_all('#\[\[([a-z0-9_]+)(?::(.+?))?\]\]#si', $template, $matches, PREG_SET_ORDER);

            foreach ($matches as $match)
            {
                if (isset($match[2])) {
                    $params = explode(',', $match[2]);
                } else {
                    $params = array();
                }

                $template = str_replace($match[0], call_user_func_array($match[1], $params), $template);
            }

            $output .= $template;
        }

        $output .= $this->_footer;

        return $output;
    }

    public function render()
    {
        echo $this->getString();
    }

    public function __toString()
    {
        return $this->getString();
    }
}